var util = require('../../../libs/util.js');
//获取应用实例
var app = getApp()
var moment = require('../../../libs/moment.min.js');
moment.locale('zh-cn');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    mode: 'unhandled',
    month: util.dateObjectformat(new Date, 'yyyy-MM'),
    warehouse: '全部项目'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    this.loadData();
  },
  bindInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    var value = e.detail.value;

    var inputtype = e.currentTarget.dataset.inputtype;
    if (inputtype == 'digit' || inputtype == 'number') {
      if (isNaN(value)) {
        value = '';
      }
    }
    item_value[item] = value;
    that.setData(item_value);
  },
  DateChange(e) {
    var that = this;
    var month = e.detail.value
    this.setData({
      month: month
    });
    that.loadData();
  },
  search: function () {
    this.loadData();
  },
  //切换收入或支出
  changeMode: function (e) {
    this.setData({
      mode: e.currentTarget.dataset.mode
    })
    this.loadData();
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '获取数据...',
      mask: true
    })
    util.getData("/atapi/price/bill/monthlyStatement", {
      'warehouse': that.data.warehouseId,
      'whName': that.data.warehouse,
      'month': that.data.month + '-01',
      'user_id': app.globalData.user_id,
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize,
      'mode': that.data.mode,
      'price_mode': 'cash',
      'CO_ID': app.globalData.CO_ID
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var count = res.data.data[1][0].COUNT;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        var _data = res.data.data[0];
        that.setData({
          dataList: _data,
          count: count,
          pageNumber: pageNumber,
          page: that.data.page == 0 ? 1 : that.data.page
        });
        that.setPageStatus();
      } else {
        that.setData({
          page: 0,
          dataList: []
        });
      }
      wx.hideLoading()
    });
  },
  sendToCarrier: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var vehicle = e.currentTarget.dataset.vehicle;
    wx.showLoading({
      title: '发送中...',
      mask: true
    })
    util.postData("/atapi/price/bill/sendToCarrier", {
      id: id,
      vehicle: vehicle
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading()
      if (res.data.success) {
        wx.showToast({
          title: "发送成功",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              that.loadData();
            }, 3000);
          }
        });
      } else {
        wx.showToast({
          title: "发送失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  //重新生成对账单-单一
  generateMSone: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    wx.showModal({
      title: '温馨提示',
      content: '确定要生成【' + name + '】的' + (moment(that.data.month).month() + 1) + '月份对账单吗？',
      success(res) {
        if (res.confirm) {
          util.postData("/atapi/price/bill/generateMonthlyStatementOne", {
            'id': id
          }, function (res, error) {
            console.log(res); console.log(error)
            if (res.data.success) {
              wx.showModal({
                title: '温馨提示',
                content: '生成' + name + '的' + (moment(that.data.month).month() + 1) + '月份对账单成功！',
                success(res) {
                  if (res.confirm) {
                    that.loadData();
                  }
                }
              });
            } else {
              wx.showModal({
                title: '温馨提示',
                content: res.data.data,
                success(res) {
                  if (res.confirm) {
                  }
                }
              });
            }
          });
        }
      }
    })

  },
  //生成对账单
  generateMS: function (e) {
    var that = this;
    if (that.data.warehouse == '' || that.data.warehouse == '全部项目') {
      wx.showModal({
        title: '温馨提示',
        content: '请选择项目',
        success(res) {
          if (res.confirm) {
          }
        }
      });
      return false;
    }
    wx.showModal({
      title: '温馨提示',
      content: '确定要生成项目【' + that.data.warehouse + '】' + (moment(that.data.month).month() + 1) + '月份对账单吗？',
      success(res) {
        if (res.confirm) {
          util.postData("/atapi/price/bill/generateMonthlyStatement", {
            'warehouse': that.data.warehouseId,
            'whName': that.data.warehouse,
            'month': that.data.month + '-01',
            'user_id': app.globalData.user_id,
            'CO_ID': app.globalData.CO_ID
          }, function (res, error) {
            console.log(res); console.log(error)
            if (res.data.success) {
              wx.showModal({
                title: '温馨提示',
                content: '生成项目【' + that.data.warehouse + '】' + (moment(that.data.month).month() + 1) + '月份对账单成功！',
                success(res) {
                  if (res.confirm) {
                    that.loadData();
                  }
                }
              });
            } else {
              wx.showModal({
                title: '温馨提示',
                content: res.data.data,
                success(res) {
                  if (res.confirm) {
                  }
                }
              });
            }
          });
        }
      }
    })

  },
  showMonthlyStatement: function (e) {
    var that = this;
    var url = e.currentTarget.dataset.url;
    wx.downloadFile({
      url: url,
      success(res) {
        wx.hideLoading();
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          }
        })
      }
    });
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  changeWarehouse: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/schedule/monitor_warehouse'
    })
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'monitor_warehouse',
      success: function (res) {
        if (res.data) {
          that.setData({
            warehouse: String(res.data.abbreviation || res.data.name).substr(0, 10),
            warehouseId: res.data.value
          });
        }
      },
      complete: function (res) {
        wx.removeStorage({
          key: 'monitor_warehouse',
          success: function (res) {
          }
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})